<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { ref, watch } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

const props = defineProps<{
  data: { x: string; y: number }[]; // 修改为对象数组
}>();

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);

// 渲染图表
function drawChart() {
  const xLabels = props.data.map((item) => item.x);
  const yValues = props.data.map((item) => item.y);

  renderEcharts({
    grid: {
      bottom: 0,
      containLabel: true,
      left: '1%',
      right: '1%',
      top: '2 %',
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 80,
        data: yValues,
        itemStyle: { color: '#4f69fd' },
      },
    ],
    tooltip: {
      axisPointer: {
        lineStyle: {
          color: '#4f69fd',
          width: 1,
        },
      },
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: xLabels,
    },
    yAxis: {
      type: 'value',
      max: Math.max(...yValues, 1000),
    },
  });
}

// 初始化 + 响应数据变化
watch(() => props.data, drawChart, { immediate: true });
</script>

<template>
  <EchartsUI ref="chartRef" />
</template>
